<template>
  <div class="pk-leveldetail">
    <div class="pk-leveldetail-header">
      <pk-button type="default" :icon="Back" @click="goBack">返回任务列表</pk-button>
    </div>
    <div class="pk-leveldetail-desc mt-24">
      <el-form label-width="100px" label-position="top" :rules="rules" ref="ruleFormRef" :model="ruleForm">
        <!-- <el-form-item label="上传图片" prop="name">
          <pk-upload :defaultList="defaultList"></pk-upload>
        </el-form-item> -->
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="ruleForm.taskName"  :disabled="lock" :rows="2" placeholder="请输入任务名称" type="textarea"/>
        </el-form-item>
        <el-form-item label="任务提示语" prop="taskContent">
          <el-input v-model="ruleForm.taskContent"  :rows="12" type="textarea"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="ruleForm.status"
            placeholder="请选择状态"
            size="default"
            style="width: 250px"
            :disabled="lock"
          >
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> 
        <el-form-item label="评分维度" prop="scoreOptionsList">
          <div class="w-b100">
            <div class="flex-row">
              <pk-button type="default" :icon="Plus" size="default" :disabled="lock" @click="addDimension">添加维度</pk-button>
              <div class="ml-12">
                <el-select
                  v-model="ruleForm.optionsType"
                  placeholder="请选择评分类型"
                  size="default"
                  style="width: 160px"
                  :disabled="lock"
                >
                  <el-option
                    v-for="item in optionstype"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div class="ml-12">
                <el-select
                  v-model="ruleForm.showType"
                  placeholder="请选择展示形式"
                  size="default"
                  style="width: 160px"
                  :disabled="lock"
                >
                  <el-option
                    v-for="item in showTypeOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </div>
            <div class="mt-12">
              <el-row v-for="(item, index) in ruleForm.scoreOptionsList" :key="index" :gutter="30">
                <el-col :span="8">
                  <div class="mb-8">
                    <el-input v-model="item.name" :disabled="lock" style="width: 100%" placeholder="请输入评分维度的名称" />
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="mb-8">
                    <el-input v-model="item.scoreNum"  :disabled="lock" style="width: 100%" placeholder="请输入评分维度的分值" />
                  </div>
                </el-col>
                <el-col :span="8" v-if="!lock">
                  <el-popconfirm
                      class="box-item"
                      title="确定要删除?"
                      placement="bottom"
                      cancel-button-text="取消"
                      confirm-button-text="确定"
                      @confirm="handlerDel(index)"
                    >
                      <template #reference>
                        <el-button type="text">删除</el-button>
                      </template>
                    </el-popconfirm>
                  
                  <!-- <div class="red-color" @click="handlerDel(index)">删除</div> -->
                </el-col>
              </el-row>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="评委" prop="judges">
          <div>
            <div>
              <pk-button type="default" :icon="Plus" :disabled="lock" size="default" @click="isBindUser=true">添加评委</pk-button>
            </div>
            <div class="mt-24 flex-row flex-wrap">
              <div v-for="item in ruleForm.judgesUserIdList" :key="index" class="mr-12 flex-auto mb-8">
                <el-tag 
                :key="item.label"
                :type="item.type"
                effect="dark"
                :closable="!lock"
                size="large"
                round
              >
              {{item.label}}{{item.value}}
              </el-tag>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="被考评人员" prop="evaluator">
          <div>
            <div class="flex-row">
              <div class="mr-12">
                <pk-button type="default" :disabled="lock"  size="default" :icon="Plus" @click="isExport=true">导入名单</pk-button>
              </div>
              <div>
                <pk-button type="default"  :disabled="lock" size="default" :icon="Plus" @click="isevaluatorUser=true">添加被考评人员</pk-button>
              </div>
            </div>
            <div class="mt-24 flex-row flex-wrap">
              <div v-for="item in ruleForm.evaluatorUserIdList" :key="index" class="mr-12 flex-auto mb-8">
                <el-tag 
                :key="item.label" 
                effect="dark"
                :closable="!lock"
                size="large"
                round
              >
                {{item.username}}
              </el-tag>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item v-if="detaildata?.status == 0 || !detaildata.status">
          <div class="flex-row justify-center align-items-center w-b100 mt-24" v-if="ruleForm">
            <div class="mr-12">
              <pk-button type="primary" :loading="loading"  size="default" @click="submitBtn">提交</pk-button>
            </div>
            <div>
              <pk-button type="danger"  size="default" @click="goBack">取消</pk-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
   <bindUser @confirm="confirm" v-if="isBindUser" @onClose="isBindUser=false"></bindUser>
   <evaluatorUser @confirm="onconfirm" v-if="isevaluatorUser" @onClose="isBindUser=false"></evaluatorUser>

   <pk-export @confirm="exconfirm" v-if="isExport" action='/scoreapi/adm/task/importEvaluator'>
    <template #template>
      <a href="/pcadmin/assessor.xls" download="assessor.xls"> 下载模板</a>
    </template>
  </pk-export>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import PkButton from '@/components/pkui/pk-button/pk-button.vue'
import { Back, View, Plus } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import bindUser from './component/bindUser.vue'
import evaluatorUser from './component/evaluatorUser.vue'
import pkUpload from '@/components/pkui/pk-upload/pk-upload.vue' 
import pkExport from '@/components/pkui/pk-export/pk-export.vue'
import { taskCreate, taskGetDeatil, taskUpdate } from '@/api/api'
const router = useRouter()
const route = useRoute()
const isBindUser = ref(false)
const lock = ref(false)
const loading = ref(false)
const isExport = ref(false)
const isevaluatorUser = ref(false)
const circleUrl = ref('https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png')
const ruleFormRef = ref(null)
const defaultList = ref([])
const props = defineProps({
  curData: {
    type: Object,
    default: () => {}
  }
})
const detaildata = ref({})
const ruleForm = ref({
  name: '',
  bannerUrl: [],
  scoreOptionsList: [],
  optionsType: 1,
  showType: 1,
  bannerUrl: "",
  judge: [],
  taskContent: '',
  evaluatorUserIdList: [],
  judgesUserIdList: [],
  assessor: []
})
const statusList = ref([
  {
    label: '草稿',
    value: 0
  },
  {
    label: '已发布',
    value: 1
  }
  // {
  //   label: '已结束',
  //   value: 2
  // }
])
const showTypeOption = ref([
  {
    label: '平铺',
    value: 2
  },
  {
    label: '下拉框',
    value: 1
  }
])

const optionstype = ref([
  {
    label: '是互斥',
    value: 1
  },
  {
    label: '不互斥',
    value: 2
  }
])
const items = ref([
  {
    label: '张三',
  }
])

// 评委管理
const confirm = (e) => {
  if (ruleForm.value.judgesUserIdList.length == 0) {
    ruleForm.value.judgesUserIdList = e
  } else {
    e.forEach(item => {
      const temp = ruleForm.value.judgesUserIdList.filter(a => a.key == item.key)
      if (temp.length < 1) {
        ruleForm.value.judgesUserIdList.push(item)
      }
    })
  } 
  isBindUser.value = false
}

// 被考平人管理
const onconfirm = (e) => {
  debugger
  if (ruleForm.value.evaluatorUserIdList.length == 0) {
    ruleForm.value.evaluatorUserIdList = e
  } else {
    e.forEach(item => {
      const temp = ruleForm.value.evaluatorUserIdList.filter(a => a == item)
      if (temp.length < 1) {
        ruleForm.value.evaluatorUserIdList.push(item)
      }
    })
  } 
  isevaluatorUser.value = false
}



const scoreOptionsList = (rule, value, callback) => {
  if (ruleForm.value.scoreOptionsList.length === 0) {
    callback(new Error('评分维度没有添加'))
    return
  }

  if (ruleForm.value.scoreOptionsList.length > 0) { 
    let data = ruleForm.value.scoreOptionsList.filter(item => !item.name || !item.scoreNum)
    if (data.length > 0) {
      callback(new Error('评分维度其中有一个没有完整'))
      return
    }
    callback()
    return
  } 
  callback()
}

const judges = (rule, value, callback) => {
  if (ruleForm.value.judgesUserIdList.length === 0) {
    callback(new Error('评委没有添加'))
    return
  } 

  callback()
}

const evaluator = (rule, value, callback) => {
  if (ruleForm.value.judgesUserIdList.length === 0) {
    callback(new Error('被考评人没有添加'))
    return
  } 

  callback()
}

const rules = ref(
  {
    taskName: [
      { required: true, message: '请输入任务名称', trigger: 'blur' },
    ],
    optionsType: [
      { required: true, message: '请选择评分类型', trigger: 'blur' },
    ],
    status: [
      { required: true, message: '请选择状态', trigger: 'change' },
    ],
    taskContent: [
      { required: true, message: '请输入任务内容', trigger: 'blur' },
    ],
    scoreOptionsList: [
      { required: true, validator: scoreOptionsList, trigger: 'blur' },
    ],
    judges: [
      { required: true, validator: judges, trigger: 'blur' },
    ], 
    evaluator: [
      { required: true, validator: evaluator, trigger: 'blur' },
    ], 
  }
)



const goBack = () => {
  router.go(-1)
} 


const handlerDel = (index) => {
  ruleForm.value.scoreOptionsList.splice(index, 1)
}

const addDimension = () => {
  ruleForm.value.scoreOptionsList.push({
    name: '',
    scoreNum: ''
  })
}


const postAdd = (data) => {
  loading.value = true
  let params = Object.assign({}, ruleForm.value)
  params.judgesUserIdList = params.judgesUserIdList.map(item => item.key)
  params.evaluatorUserIdList = params.evaluatorUserIdList.map(item => item.username )
  taskCreate({
    ...params
  }).then(res => {
    loading.value = false
    router.go(-1)
  }).catch(err => {
    loading.value = false
  })
}

const postEdit = (data) => {
  const { id } = route.query
  loading.value = true
  let params = Object.assign({}, ruleForm.value)
  params.judgesUserIdList = params.judgesUserIdList.map(item => item.key)
  params.evaluatorUserIdList = params.evaluatorUserIdList.map(item => item.username) 
  params.id = id
  taskUpdate(params).then(res => {
    router.go(-1)
    loading.value = false
  }).catch(err => {
    loading.value = false
  })
}

const submitBtn = () => {
  const { id } = route.query
  ruleFormRef.value.validate((res) => {
    if (res) {
      if (id) {
      postEdit(res)
    } else {
      postAdd(res)
    }
    }
  });
}

const getDetail = () => {
  const { id } = route.query
  taskGetDeatil({
    id: id
  }).then(res => {
    detaildata.value = res.resData
    if (res.resData.status > 0) {
      lock.value = true
    } 
    if (res.resData.bannerUrl) {
      defaultList.value = [{
        url: res.resData.bannerUrl
      }] 
    }
    
    ruleForm.value.bannerUrl = res.resData.bannerUrl
    ruleForm.value.taskName = res.resData.taskName
    ruleForm.value.taskContent = res.resData.taskContent
    ruleForm.value.status = res.resData.status
    ruleForm.value.optionsType = res.resData.optionsType
    ruleForm.value.showType = res.resData.showType
    ruleForm.value.judgesUserIdList = res.resData.judgesList.map(item => {
      return {
        ...item,
        key: item.id,
        value: item.phone,
        label: item.username
      }
    })
    ruleForm.value.scoreOptionsList = res.resData.scoreOptionsList
    ruleForm.value.evaluatorUserIdList = res.resData.evaluatorList.map(item => {
      return {
        ...item,
        username: item.username
      }
    })
  })
}

const exconfirm = (e) => {
  let data = e.resData.map(item => {
    return {
      username: item.username
    }
  })
  let newData = []
  // 过滤已存在的人
  data.forEach(item => {
    let tempdata = ruleForm.value.evaluatorUserIdList.find(a => a.username == item.username)
    if (!tempdata) {
      newData.push(item)
    }
  })
  // 过滤评委的人

  isExport.value = false
  ruleForm.value.evaluatorUserIdList.push(...newData)

}

onMounted(() => {
  const { id } = route.query
  if (id) {
    getDetail()
  }
}) 

</script>

<style lang="scss" scoped>

</style>